﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FanaticRock.Core.DI
{

    public static class ServiceProviderBuilder
    {

        public static IEnumerable<ClassDIInfo> Resolve(IEnumerable<Assembly> assemblies)
        {
            if (assemblies == null) return new ClassInterfaceDIPair[0];
            return assemblies.SelectMany(a => GetDeclaredPairs(a));
        }

        private static IEnumerable<ClassDIInfo> GetDeclaredPairs(Assembly assembly)
        {
            var types = assembly.GetTypes();
            foreach (var type in types)
            {
                var hasAtt = TryGetClassTypeHasInjectMeAttribute(type, out var pair);
                if (hasAtt == false) continue;
                yield return pair;
            }
        }


        ///<summary>尝试获得指定类型的是否有 InjectMe 的标记。</summary>
        private static bool TryGetClassTypeHasInjectMeAttribute(Type type, out ClassDIInfo pair)
        {
            pair = null;
            var injectMeAttribute = type.GetCustomAttribute<InjectMeAttribute>();
            if (injectMeAttribute == null) return false;
            var interfaceType = injectMeAttribute.InterfaceType;
            var liftTimeType = injectMeAttribute.LifeTimeType;
            if (interfaceType == null)
            {
                pair = new ClassDIInfo(type);
            }
            else
            {
                pair = new ClassInterfaceDIPair(type, interfaceType);
            }

            pair.LiftTimeType = liftTimeType;

            return true;

        }
    }
}
